import { createContext, useActionState, useContext } from "react";
import { useNavigate } from "react-router";

const authContext = createContext(null);

export const useAuth = ()=>useContext(authContext)

export function AuthContext({children}){
    const url = "http://127.0.0.1:8000/api/v1";
    const nav = useNavigate()

    const isLogin = () =>{
        return authInfo || JSON.parse(localStorage.getItem("authInfo"))
    }
    
    const login = async (prevValue,data)=>{
        const response = await fetch(`${url}/login`,{
            method: "post",
            headers: {
                "Content-Type" : "application/json"
            },
            body: JSON.stringify(data)
        })
        if(response.status===200){
            const body = await response.json()
            const _authInfo = {
                token: body.data.token,
                token_uuid: body.data.token_uuid,               
                user: body.data.user
            }
            localStorage.setItem("authInfo",JSON.stringify(_authInfo))
            nav(-1)
            return _authInfo
        }
        return null
    }


    const [authInfo,logAction,isPending] = useActionState(action,JSON.parse(localStorage.getItem('authInfo')));

    const logout = async (prev,data)=>{
        if(!authInfo) return null

        const response = await fetch(`${url}/logout`,{
            method: "get",
            headers: {
                "X-Request-ID": authInfo.token_uuid,
                "Authorization": `Bearer ${authInfo.token}`
            }
        })
        if(response.status===200){
            localStorage.removeItem("authInfo")
              return null
        }
        return authInfo
    }

    async function action(prev, formData){
        let data = null
        if(formData instanceof FormData){
            data = Object.fromEntries(formData.entries()); 
        }
        if(!data) return null
        if(data.type==="login"){
           return await  login(prev,data)
        }
        else{
            return await logout(prev,data)
        }
    }

    return (
        <authContext.Provider value={{authInfo,logAction,isPending}}>
            {children}
        </authContext.Provider>
    )
} 